<?php
require_once "./header.php";
$conn = connect_to_db();

//此处开始设置监控访问日志需要的监控代码----------------------------------------
$PKey = 'wanmi';//项目key值
$splitFlag = false;//是否分表 true分表 false没有分表
$pvuvLogObj = new pvuvLog($PKey, $splitFlag);
$pvuvLogObj->visitWeixinID = $openid;//访问当前页面的用户
$pvuvLogObj->kmResult = "";//页面中需要保存的数据;
$url = $_SERVER['PHP_SELF'];
$pageName = substr($url, strrpos($url, '/') + 1);
$pvuvLogObj->urlID = $PKey . "_istore_next_$pageName";//页面ID 项目key_页面名称


//CONM是wanmi自身数据库通过bs_member表查询
$conm = mysqli_connect($sqlHost , $sqlUser , $sqlPsd,'marlboro_wanmi');
$query = "SELECT act_code,verify,nickname,headimgurl,integral FROM bs_member WHERE openid = '$openid'";
$result = mysqli_query($conm,$query);

$confirmRule = 0;

$header = '';
if(is_resource($result)||mysqli_num_rows($result) == 1){
	$member = mysqli_fetch_assoc($result);
	if($member['act_code'] != 'unsubscribe'){
		if($member['verify'] == '1'||$member['verify'] == '0'){
			$is_member = '1';
//判断是否答应条款
			$query = "SELECT openid FROM bs_confirm_rule WHERE openid = '$openid' AND activity_name = '$wanmiProjectEn'";
			$result = mysqli_query($conm,$query);
			if(mysqli_num_rows($result) != 0){

				$confirmRule = 1;
			}else{
//				$header = "http://wanmiclub.lovemojito.com/wanmi_user_rule/confirmRule.php?callback="."http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
			}

		}else{
			$is_member = '0';
			$header = "http://wanmiclub.lovemojito.com/wx/index.php?s=/Home/member/f1bind";
		}
	}else{
		$header='error.html';
	}
}else{
//    echo $query."</br>";
	$header='error.html';
}

//是否兑换过
$isCost = 0;
$query = "SELECT * FROM bs_integral_store_next_user WHERE openid = '$openid'";
$result = mysqli_query($conm,$query);
if(mysqli_num_rows($result) != 0){
	$isCost = 1;
		$header = 'index.php';

}

if($header!=''){
	header('Location:'.$header);
	echo $header;
	$pvuvLogObj->kmResult = 'Location:'.$header;
	$pvuvLogObj->saveLog();
	exit();
}

$unixTime = time();
$ajaxKey = 'dkn23m@63!ds';
$token = md5($openid.$unixTime.$ajaxKey);

$thisMonth = date('Y_m');
$firstday = date("Y-m-01");
$lastday = date("Y_m",strtotime("$firstday -1 day"));

$template=0;
if($_GET['platform'] == 'template'){
	$template=1;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>万迷聚乐部</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <script src="js/responsive.js"></script>
    <link rel="stylesheet" href="css/exchangePage.css">
    <style>
        .choice-right{
            background-color: #a4a4a4;
        }
        #LastThank{
            position: absolute;
            left: 0;
            top: 0;
            padding: 0px;
            overflow: hidden;
            height: 100%;
            width: 100%;
            background: url("img/exchangePage/thank-you-bg.png")repeat-y center/cover;
        }
        .thank-content{
            /*text-align: center;*/
            position: relative;
            width: 70%;
            height: 32rem;
            /*margin-bottom: 4rem;*/
            /*margin: 12vw 18vw;*/
            margin: 1.2rem auto;
            background: url("img/exchangePage/thank-you-content.png")no-repeat center center/contain;
        }
        .rule-content{
            display: none;
            background-color: white;
            width: 96%;
            text-align: center;
            margin: 10px 0;
            border-radius: 25px;
            min-height: 100%;
            overflow-y: scroll;
        }
        .rule-content img:first-child{
            margin: 20px 0;
            width: 90%;
        }
        .rule-content img:last-child{
            width: 29%;
            margin:	5px 0 20px ;
        }
        .rule-content input{
            vertical-align: -2px;
            margin-right: 5px;
        }
        .rule-content span{
            font-size: 1rem;
            font-weight: 300;
        }
        .back{
            position: absolute;
            float: right;
            top: 4vw;
            right: 4vw;
        }
        #ExchComplete{
            cursor: pointer;
        }
        .bottom-wrap{
            height: 4rem;
            width: 100%;
            background: url("img/exchangePage/thank-you-bg.png")repeat-y center/cover;
            position: fixed;
            bottom: 0;
            padding-top: 1rem;
        }
    </style>
</head>
<body>
<div id="exchange" class="exchange" >
    <div class="center">
        <img id="goBack" src="img/exchangePage/back.png" class="go-back">
        <img class="ExchTitle" src="img/exchangePage/exchangePage-title.png" >
    </div>
    <section class="body">
        <!--奖品显示栏-->
        <div class="body-exchange">
            <!--左-->
            <img id="prize-left" src="" class="prize-one" >
            <div class="choice choice-left">
                <img src="img/exchangePage/yes.png" class="yes" >
            </div>
            <!--右-->
            <img id="prize-right" src="" class="prize-two">
            <div class="choice choice-right">
                <img src="img/exchangePage/yes.png" class="yes no" >
            </div>
        </div>
        <!--姓名电话栏-->
        <div>
            <img src="img/exchangePage/name-bg.png" class="name-bg">
            <img src="img/exchangePage/name.png" class="name">
            <input id="user-name" type="text" class="user-name" placeholder=""/>
            <img src="img/exchangePage/tel-bg.png" class="tel-bg">
            <img src="img/exchangePage/tel.png" class="tel">
            <input id="user-tel" type="tel" class="user-tel" placeholder="请确认该手机号为万迷本人使用 "/>
        </div>
        <!--地址栏-->
        <div id="user-address" style="display: none;">
            <img src="img/exchangePage/address.png" class="address" >
            <input id="address" type="text" class="user-address" placeholder="请填写奖品收货地址"/>
        </div>
        <a id="choice-sure"><img  src="img/exchangePage/sure.png" class="sure"></a>
    </section>
</div>
<!--兑换成功弹窗-->
<div id="exchangeSucceed" class="succeed">
    <img src="img/exchangePage/ExchangeSuccess.png" class="digital" width="80%" style="display: none" >
    <img src="img/exchangePage/ExchangeSuccess2.png" class="thing" width="80%" style="display: none;" >
    <img id="ExchComplete" src="img/exchangePage/ExchSuccessSure.png" >
</div>

<!--最终跳转-->
<div id="LastThank" style="display: none;">
    <div class="thank-content"></div>
    <section class="bottom-wrap">
        <a id="agree-keep"><img src="img/exchangePage/thank-you-agree.png" width="25%"  style="position: relative;left: 18vw;"></a>
        <a id="refuse-keep"><img src="img/exchangePage/thank-you-refuse.png" width="25%"  style="position: relative;float: right;right: 18vw;"></a>
    </section>
</div>
<!--规则弹窗-->
<div id="rule-bPopup" class="rule-content">
    <?php if($template){ ?>
        <img src="img/ruleContent2.png" ><br/>
    <?php }else{ ?>
    <img src="img/ruleContent.png" ><br/>
    <?php } ?>
    <input type="checkbox"   checked="checked" id="checkbox"/><span>我已阅读并同意该协议</span><br>
    <img id="agree-return" src="img/agree-rule.png" >
</div>
</body>
</html>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js?v=1?"></script>
<script src="js/jquery.bpopup.min.js"></script>
<script>
    var isCost = '<?php echo $isCost; ?>';
    var openid = '<?php echo $openid; ?>';
    var confirmRule = '<?php  echo $confirmRule;  ?>';

    console.log(confirmRule);
    if(confirmRule=='0'){
        buttonLog('window-exchange-rule');

        $('#rule-bPopup').bPopup({
            // positionStyle:'fixed',
            modalClose: false,
            opacity:0.6

        });
    }
/*    if(isCost == '1'){
        $('#exchangeSucceed').bPopup({
            modalClose: false,
            opacity: 0.6
        });
    }*/
    $('#agree-return').on('click',function () {
        buttonLog('button-exchange-rule');

        if($(":checkbox").get(0).checked){
            if(confirmRule=='0') {

                $.ajax({
                    url: "http://wanmiclub.lovemojito.com/wx/index.php?s=/Home/IntegralStoreNext/confirmRule",
                    method: 'post',
                    dataType: 'json',
                    data: {'openid': '<?php echo $openid;?>'},
                    success: function (res) {
                        confirmRule = 1;
                    },
                    error: function () {
                        alert('当前网络状况较差，请检查网络后再试!');
                        return false;
                    }
                });
                $("#confirm").attr('disabled', 'true');
            }
            $('#rule-bPopup').bPopup().close();

        }


    })

    $(function (){
        var value,     //奖品等级标志
            prize = 0; //奖品选择标志
        var exchange ={
            //提取cookie
            getCookie: function (cname){
                var name = cname + "=";
                var ca = document.cookie.split(';');
                for(var i=0; i<ca.length; i++){
                    var c = ca[i].trim();
                    if (c.indexOf(name) == 0)
                        return c.substring(name.length,c.length);
                }
                return "";
            },
            go: function (){
                $('#goBack').on('click',function () {
                    window.history.go(-1);
                });
            },
            input_judge: function (){
                value = Number(this.getCookie("value"));//字符串转数字

                $('#choice-sure').on('click',function (e) {
                    e.preventDefault();

                    if(confirmRule =='0'){
                        alert('请阅读兑换条款并同意后兑换')
                    }
                    var name = $("#user-name").val();
                    var phone = $("#user-tel").val();
                    var local=$('#address').val();
                    var judge = true;
                    //输入判断
                    if ($('#user-name').val() == ''){
                        $('#user-name').focus();
                        alert("请填写您的姓名");
                        judge = false;
                        return false;
                    }
                    if(!/^[1][3,4,5,7,8][0-9]{9}$/.test($("#user-tel").val())){
                        $("#user-tel").focus();
                        alert('请输入正确的手机号');
                        judge = false;
                        return false;
                    }
                    if (value == 3 || value ==4){
                        if ($('#address').val() == ''){
                            $('#address').focus();
                            alert("请填写您的收货地址");
                            judge = false;
                        }
                    }
                    if (judge){
                        let costItem = '';
                        console.log(value);
                        switch (value) {
                            case 1:
                                if(prize==1) {
                                    costItem='QQ音乐会员兑换券';
                                } else{
                                    costItem='10元手机话费'
                                }
                                break;
                            case 2:
                                if(prize==1) {
                                    costItem='30元手机话费'

                                } else{
                                    costItem='星巴克电子饮品券';

                                }
                                break;
                            case 3:
                                if(prize==1) {
                                    costItem='zippo定制打火机'
                                } else{
                                    costItem='LAMY定制钢笔';
                                }
                                break;
                            case 4:
                                if(prize==1) {
                                    costItem='外星人游戏鼠标'
                                } else{
                                    costItem='JBL蓝牙耳机';
                                }
                                break;
                            default:
                                costItem='';
                                break;
                        }
                        buttonLog('button-confirm-buy'+costItem);

                        if(costItem!=''){
                            $.ajax({
                                type:"get",
                                url:"http://wanmiclub.lovemojito.com/wx/index.php?s=Home/IntegralStoreNext/integralStoreBuyItem",
                                dataType:'JSON',
                                async:false,
                                data:{'type':costItem,'name':name,'phone':phone,'local':local,'openid':openid},
                                success:function (res) {
                                    if(res['errcode']=='0'){
                                        if(value == 4 ||value==3){
                                            $('.thing').show();
                                            $('.digital').hide();
                                        }else{
                                            $('.thing').hide();
                                            $('.digital').show();
                                        }
                                        $('#exchangeSucceed').bPopup({
                                            modalClose: false,
                                            opacity: 0.6
                                        });
                                    }
                                    else if(res['errcode']=='333'){
                                        alert('积分不足');
                                        return false;
                                    }
                                    else if(res['errcode']=='222'){
                                        alert('商品无库存');
                                        return false;
                                    }
                                    else if(res['errcode']=='212'){
                                        alert('兑换失败，一人只有一次兑换机会');
                                        return false;
                                    }
                                    else{
                                        alert('网络出错',res['errcode']);
                                        return false;
                                    }

                                },
                                error:function (res) {
                                    alert('网络错误500');
                                    return false;
                                }
                            })
                        }else{
                            alert('网络错误，请重新刷新页面');
                            return false;
                        }


                    }
                });
            },
            //奖品选择
            prize_choice: function (){
                $('.choice-left').on('click',function (e) {
                    e.preventDefault();
                    $(this).css("background-color","#d7182a");
                    $('.choice-right').css("background-color","#a4a4a4");
                    prize = 0;
                    console.log(prize);
                });
                $('.choice-right').on('click',function (e) {
                    e.preventDefault();
                    $(this).css("background-color","#d7182a");
                    $('.choice-left').css("background-color","#a4a4a4");
                    prize = 1;
                    console.log(prize);
                });
            },
            init: function (){
                this.go();
                var $_left = $('#prize-left');
                var $_right = $('#prize-right');
                var $_address = $('#user-address');
                value = Number(this.getCookie("value"));//字符串转数字
                switch(value){
                    case 1:
                        console.log(value);
                        document.getElementById('prize-left').src = 'img/exchangePage/￥10.png';
                        $_left.addClass('prize-10');
                        document.getElementById('prize-right').src = 'img/exchangePage/qqMusic.png';
                        $_right.addClass('prize-qq');
                        $_address.hide();break;
                    case 2:
                        console.log(value);
                        document.getElementById('prize-left').src = 'img/exchangePage/Starbucks.png';
                        $_left.addClass('prize-star');
                        document.getElementById('prize-right').src = 'img/exchangePage/￥30.png';
                        $_right.addClass('prize-30');
                        $_address.hide();break;
                    case 3:
                        console.log(value);
                        document.getElementById('prize-left').src = 'img/exchangePage/pen.png';
                        $_left.addClass('prize-pen');
                        document.getElementById('prize-right').src = 'img/exchangePage/lighter.png';
                        $_right.addClass('prize-lighter');
                        $_address.show();break;
                    case 4:
                        console.log(value);
                        document.getElementById('prize-left').src = 'img/exchangePage/headset.png';
                        $_left.addClass('prize-headset');
                        document.getElementById('prize-right').src = 'img/exchangePage/mouse.png';
                        $_right.addClass('prize-mouse');
                        $_address.show();break;
                    default: break;
                }
                this.prize_choice();
                this.input_judge();
                $('#ExchComplete').on('click',function (e) {
                    buttonLog('button-ExchComplete');
                    e.preventDefault();
                    $('#exchangeSucceed').bPopup().close();
                    $('#LastThank').bPopup({
                        // positionStyle:'fixed',
                        modalClose: false
                    });
                });
            },
            upload: function (){
                var height = window.screen.availHeight;
                //背景高度适配
                document.getElementById('exchange').style.height = height + 'px';
                document.getElementById('LastThank').style.height = height + 'px';
//                console.log(height);
                $('.body').css('height',height-99 +'px');
                this.init();
            }
        };
        exchange.upload();
    }());

    $('#agree-keep').on('click',function () {
        buttonLog('button-agree-keep');
        window.location.href = 'index.php';
    });
    $('#refuse-keep').on('click',function () {
        buttonLog('button-refuse-keep');
        window.location.href = 'index.php';
    });

    function buttonLog(button) {
        $.ajax({
            type:"get",
            url:"http://wanmiclub.lovemojito.com/wx/index.php?s=Home/IntegralStoreNext/integralStoreButton",
            dataType:'JSON',
            async:false,
            data:{'button':button,"openid":openid},
            success:function (data) {
                console.log(data);
            },
            error:function (data) {
                console.log('error');
            }
        })
    }

</script>
<?php
$pvuvLogObj->kmResult = json_encode($member,JSON_UNESCAPED_UNICODE);
$pvuvLogObj->saveLog();
?>